<template>
  <!--  <div class="min-h-screen bg-gray-50">-->
  <div>
    <!-- 顶部操作区 -->
    <div class="mb-6 flex items-center justify-between">
      <div class="flex items-center gap-4">
        <el-button type="primary" class="!rounded-button whitespace-nowrap" @click="handleCreate">
          <el-icon class="mr-1">
            <Plus />
          </el-icon>新建汇报材料任务
        </el-button>
        <el-button type="success" @click="exportExcel">
          <el-icon>
            <document />
          </el-icon>导出Excel
        </el-button>
      </div>
      <div class="flex items-center gap-4">
        <div class="relative">
          <el-input v-model="searchKey" placeholder="搜索任务名称" class="w-64" :prefix-icon="Search"
            @keyup.enter="handleSearch" />
        </div>
        <el-select v-model="status" placeholder="状态" class="w-32" @change="handleStatusChange">
          <el-option label="全部" :value="1" />
          <el-option label="我的" :value="2" />
        </el-select>
        <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" class="w-72" @change="handleDateChange" format="YYYY-MM-DD"
          value-format="YYYY-MM-DD" />
      </div>
    </div>
    <!-- 表格区域 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="creator" label="项目名称" width="120" align="center">
        <template #default="{ row }">
          {{ row.projectName }}
        </template>
      </el-table-column>
      <el-table-column label="任务名称" min-width="300" align="left">
        <template #default="{ row }">
          <div class="flex items-center">
            <span>{{ row.materialName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="creator" label="创建人" width="100" align="center">
        <template #default="{ row }">
          {{ row.itemReportMaterialCreateUserName }}
        </template>
      </el-table-column>
      <el-table-column prop="creator" label="审核人" width="100" align="center">
        <template #default="{ row }">
          {{ row.itemReportMaterialAuditUserName }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" align="center">
        <template #default="{ row }">
          {{ row.createAt }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="审核时间" width="160" align="center">
        <template #default="{ row }">
          {{ row.processTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="getStatusText(row).type">{{ getStatusText(row).text }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="370" fixed="right" align="center">
        <template #default="{ row }">
          <el-button :disabled="row.itemReportMaterialStatus === 2 || row.itemReportMaterialStatus === 4" type="success"
            plain class="!rounded-button whitespace-nowrap bg-green-500 hover:bg-green-600" size="small"
            @click="handleOnlineResources(row)" style="margin-bottom: 5px;">
            <el-icon class="mr-1">
              <Promotion />
            </el-icon>
            汇报材料
          </el-button>
          <el-button color="#97804f" class="!rounded-button whitespace-nowrap bg-blue-500 hover:bg-blue-600"
            size="small" @click="handleLookFileReview(row)" style="margin-bottom: 5px;color: #fff;">
            <el-icon class="mr-1">
              <Stamp />
            </el-icon>查看材料
          </el-button>
          <el-button v-if="row.itemReportMaterialStatus !== 4" color="#ff9900"
            class="!rounded-button whitespace-nowrap bg-blue-500 hover:bg-blue-600" size="small"
            @click="handleFileReview(row)" style="margin-bottom: 5px;color: #fff;">
            <el-icon class="mr-1">
              <Stamp />
            </el-icon>审核
          </el-button>
          <el-button v-if="row.itemReportMaterialStatus === 4 && row.creatorrCommentToProcessor == ''" color="#2db7f5"
            class="!rounded-button whitespace-nowrap bg-blue-500 hover:bg-blue-600" size="small"
            @click="handleToCreator(row)" style="margin-bottom: 5px;color: #fff;">
            <el-icon class="mr-1">
              <Document />
            </el-icon>对审核人评价
          </el-button>
          <el-button v-if="row.itemReportMaterialStatus !== 4" type="primary" class="!rounded-button whitespace-nowrap"
            size="small" @click="handleEdit(row)" style="margin-bottom: 5px;">
            <el-icon class="mr-1">
              <Edit />
            </el-icon>编辑
          </el-button>
          <el-button v-if="row.itemReportMaterialStatus !== 4" type="danger"
            class="!rounded-button whitespace-nowrap bg-blue-500 hover:bg-blue-600" size="small"
            @click="handleReturnMeetingNotes(row)">
            <el-icon class="mr-1">
              <RefreshRight />
            </el-icon>撤回
          </el-button>
          <el-button type="warning" class="!rounded-button whitespace-nowrap bg-green-500 hover:bg-green-600"
            size="small" @click="handleHistory(row)">
            <el-icon class="mr-1">
              <Timer />
            </el-icon>历史
          </el-button>
          <el-button type="danger" class="!rounded-button whitespace-nowrap bg-red-500 hover:bg-red-600" size="small"
            @click="handleDelete(row)">
            <el-icon class="mr-1">
              <Delete />
            </el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-4 flex justify-end">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next"
        @current-change="handleBugListPageChange" />
    </div>
    <!-- 文件审核弹窗 -->
    <el-dialog v-model="fileReviewVisible" title="文件审核" width="800px">
      <div class="mb-4">
        <el-table :data="currentFiles" style="width: 100%">
          <el-table-column prop="name" label="文件名称" min-width="180">
            <template #default="{ row }">
              <div class="flex items-center">
                <el-button type="primary" link class="!p-0 text-blue-500 hover:text-blue-600" @click="previewFile(row)">
                  {{ row.name }}
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="submitter" label="提交人" width="120" />
          <el-table-column prop="size" label="文件大小" width="100" />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <div class="flex items-center gap-2">
                <el-button type="info" class="!rounded-button whitespace-nowrap" size="small"
                  @click="handlePreviewDocument(handleFileName(row.downloadUrl).url)">
                  <el-icon class="mr-1">
                    <View />
                  </el-icon>预览
                </el-button>
                <el-button type="info" class="!rounded-button whitespace-nowrap" size="small"
                  @click="handleDownload(row)">
                  <el-icon class="mr-1">
                    <Download />
                  </el-icon>下载
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="handleReject">
            <el-icon class="mr-1">
              <Close />
            </el-icon>驳回
          </el-button>
          <el-button type="success" @click="handleApproveAll">
            <el-icon class="mr-1">
              <Check />
            </el-icon>通过
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看审核材料弹窗 -->
    <el-dialog v-model="lookFileReviewVisible" title="审核文件" width="1200px">
      <div class="mb-4">
        <el-table :data="currentFiles" style="width: 100%">
          <el-table-column prop="name" label="文件名称" min-width="180">
            <template #default="{ row }">
              <div class="flex items-center">
                <el-button type="primary" link class="!p-0 text-blue-500 hover:text-blue-600" @click="previewFile(row)">
                  {{ row.name }}
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="submitter" label="提交人" width="120" />
          <el-table-column prop="size" label="文件大小" width="100" />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <div class="flex items-center gap-2">
                <el-button type="info" class="!rounded-button whitespace-nowrap" size="small"
                  @click="handlePreviewDocument(handleFileName(row.downloadUrl).url)">
                  <el-icon class="mr-1">
                    <View />
                  </el-icon>预览
                </el-button>
                <el-button type="info" class="!rounded-button whitespace-nowrap" size="small"
                  @click="handleDownload(row)">
                  <el-icon class="mr-1">
                    <Download />
                  </el-icon>下载
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <!-- 历史记录弹窗 -->
    <el-dialog v-model="historyDialogVisible" title="操作历史" width="800px">
      <el-scrollbar height="70vh">
        <el-timeline>
          <el-timeline-item v-for="(activity, index) in currentHistory" :key="index" :timestamp="activity.createAt"
            :type="getHistoryItemTypeRandomByLength(activity.itemRequirementOnlieTaskUserName)">
            <div class="flex flex-col gap-1">
              <div class="font-medium text-gray-900">
                <span class="ml-2 text-gray-600">{{ activity.itemRequirementOnlieTaskUserName }}</span>
              </div>
              <div class="text-gray-600">{{ activity.itemRequirementOnlieTaskLog }}</div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </el-scrollbar>
    </el-dialog>
    <!-- 新建上线任务弹窗 -->
    <el-dialog v-model="createTaskVisible" title="新建上线任务" width="500px">
      <el-form :model="newTask" label-width="100px">
        <el-form-item label="所属项目" required>
          <el-select v-model="newTask.itemItemId" placeholder="请选择项目" class="w-full" filterable>
            <el-option v-for="item in allItems" :key="item.ID" :label="item.itemName" :value="item.ID" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务名称" required>
          <el-input v-model="newTask.onlineTaskName" placeholder="请输入任务名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="createTaskVisible = false">取消</el-button>
          <el-button type="primary" class="!rounded-button whitespace-nowrap" @click="confirmCreateTask">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 提交任务审核弹窗 -->
    <el-dialog v-model="submitAuditVisible" title="提交审核" width="500px">
      <el-form label-width="100px">
        <el-form-item label="审核人" required>
          <el-select v-model="submitAuditUUID" placeholder="请选择审核人" class="w-full" filterable>
            <el-option v-for="item in availableAuditPersons" :key="item.uuid" :label="item.nickName"
              :value="item.uuid" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="createTaskVisible = false">取消</el-button>
          <el-button type="primary" class="!rounded-button whitespace-nowrap" @click="confirmCreateTask">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改上线任务弹窗 -->
    <el-dialog v-model="updateTaskVisible" title="修改上线任务" width="500px">
      <el-form :model="newTask" label-width="100px">
        <el-form-item label="任务名称" required>
          <el-input v-model="newTask.onlineTaskName" placeholder="请输入任务名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="updateTaskVisible = false">取消</el-button>
          <el-button type="primary" class="!rounded-button whitespace-nowrap" @click="confirmUpdateTask">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 评分和评语对话框 -->
    <el-dialog v-model="approveDialogVisible" title="对项目经理评分" width="600px" :close-on-click-modal="false">
      <el-form :model="approveForm" label-width="110px">
        <el-form-item label="自评分配比" prop="processorMySelfNumber" required>
          <el-input-number v-model="approveForm.processorMySelfNumber" :min="0" :max="100" placeholder="1-100分" />
          （备注：任务分值：1-100；这个材料我帮项目经理多少）
        </el-form-item>
        <el-form-item label="对项目经理评分" prop="processorCommentToRating" required>
          <el-input-number v-model="approveForm.processorCommentToRating" :min="0" :max="100" placeholder="1-100分" />
          （备注：任务分值：1-100；）
        </el-form-item>
        <el-form-item label="对项目经理评语" prop="processorCommentToProcessor" required>
          <el-input v-model="approveForm.processorCommentToProcessor" type="textarea" :rows="4" placeholder="请输入评语" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApprove">确定</el-button>
      </template>
    </el-dialog>
    <!-- 对审核人评分 -->
    <el-dialog v-model="approveCreatorDialogVisible" title="对审核人评分" width="600px" :close-on-click-modal="false">
      <el-form :model="approveCreatorForm" label-width="130px">
        <el-form-item label="对审核人评分配比" prop="processorMySelfNumber">
          <el-input-number v-model="approveCreatorForm.managerCommentToCreatorNumber" :min="0" :max="100"
            placeholder="1-100分" />
          （备注：任务分值：1-100；这个材料审核人帮我多少）
        </el-form-item>
        <el-form-item label="对审核人评分" prop="processorCommentToRating">
          <el-input-number v-model="approveCreatorForm.creatorrCommentToRating" :min="0" :max="100"
            placeholder="1-100分" />
          （备注：任务分值：1-100；）
        </el-form-item>
        <el-form-item label="对审核人评语" prop="processorCommentToProcessor">
          <el-input v-model="approveCreatorForm.creatorrCommentToProcessor" type="textarea" :rows="4"
            placeholder="请输入评语" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="approveCreatorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCommentApprove">确定</el-button>
      </template>
    </el-dialog>
    <!-- 上线分支模态框 -->
    <el-dialog v-model="showDialog" title="上线资源" width="50%" :close-on-click-modal="false">
      <el-form :model="onlineRemarkForm" label-width="120px" label-position="left" ref="formRef">
        <el-form-item label="审核人" required>
          <el-select v-model="onlineRemarkForm.submitAuditUUID" placeholder="请选择审核人" class="w-full" filterable
            :disabled="isUploading">
            <el-option v-for="item in availableAuditPersons" :key="item.uuid" :label="item.nickName"
              :value="item.uuid" />
          </el-select>
        </el-form-item>
        <!-- 汇报材料上传 -->
        <el-form-item label="汇报材料" prop="resources">
          <el-upload v-model:file-list="fileList" class="upload-demo" drag multiple :auto-upload="true"
            :http-request="customUpload" :on-success="handleUploadSuccess" :on-error="handleUploadError"
            :disabled="isUploading">
            <div class="el-upload__text">
              拖拽文件到此处或<em>点击上传</em>
            </div>
          </el-upload>
          <!-- 上传进度条 -->
          <div v-if="isUploading" class="mt-4 p-4 rounded-lg upload-progress-container">
            <div class="flex items-center justify-between mb-3">
              <div class="flex items-center">
                <el-icon class="mr-2 text-blue-500 animate-spin">
                  <Loading />
                </el-icon>
                <span class="text-sm font-medium text-gray-700">文件上传中</span>
              </div>
              <span class="text-sm font-bold text-blue-600 bg-blue-100 px-3 py-1 rounded-full shadow-sm">{{ uploadProgress }}%</span>
            </div>
            
            <!-- 自定义进度条 -->
            <div class="relative">
              <div class="w-full bg-gray-200 rounded-full h-4 overflow-hidden shadow-inner">
                <div 
                  class="h-full upload-progress-bar rounded-full transition-all duration-500 ease-out relative"
                  :class="{ 'upload-progress-glow': uploadProgress > 0 }"
                  :style="{ width: uploadProgress + '%' }"
                >
                </div>
              </div>
              <!-- 进度条上的光效 -->
              <div 
                v-if="uploadProgress > 0 && uploadProgress < 100"
                class="absolute top-0 h-4 w-6 bg-white opacity-70 rounded-full animate-pulse shadow-lg"
                :style="{ left: uploadProgress + '%', transform: 'translateX(-50%)' }"
              ></div>
            </div>
            
            <div class="mt-3 text-sm text-gray-600">
              <div v-if="uploadingFiles.length > 0" class="flex items-center">
                <el-icon class="mr-1 text-green-500">
                  <Document />
                </el-icon>
                <span class="truncate max-w-xs font-medium">{{ uploadingFiles[uploadingFiles.length - 1] }}</span>
              </div>
              <div class="mt-1 flex items-center text-amber-600">
                <el-icon class="mr-1">
                  <Warning />
                </el-icon>
                <span class="font-medium">请勿关闭页面或刷新浏览器</span>
              </div>
            </div>
          </div>
        </el-form-item>
        <!-- 上线内容备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="onlineRemarkForm.materialMsg" type="textarea" :rows="3" placeholder="请填写想要说的话"
            maxlength="200" show-word-limit :disabled="isUploading" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false" :disabled="isUploading">取消</el-button>
          <el-button type="primary" @click="handleSubmitOnlineRemark" :disabled="isUploading">
            {{ isUploading ? '上传中...' : '确认' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search, Loading, Document, Warning } from '@element-plus/icons-vue';
import {
  GetRoleUsers,//根据权限获取人员信息
  // 汇报任务接口
  PostCreateReportMaterial,// 创建汇报任务
  PostUploadReportMaterialFile,// 提交汇报任务
  GetDeleteReportMaterialById,// 删除上线任务
  PostgetReportMaterialList,// 获取汇报任务列表，可以根据条件获取自己或者所有人的
  ExportReportMaterialList,// 导出汇报材料
  PostUpdateReportMaterialName,// 修改汇报任务的名称
  GetGetReportMaterialLogs,// 查看操作历史记录
  PostAuditNotBy,// 审核不通过
  PostAuditBy,// 审核通过
  PostAuditToCreator,// 审核通过
  GetReturnReportMaterialAudit,// 撤销审核任务

} from "@/api/newDemands/index";
import {
  getItemList, //获取所有的待填写任务列表
} from "@/api/common/index";
import { onBeforeMount } from 'vue';
import { handleFileName, openPreviewInNewWindow } from "@/utils/utils";


const loading = ref(false);
const searchKey = ref('');
const status = ref('');
const dateRange = ref(['', '']);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);
const openOnlineTask = ref();
const auther = ref();
auther.value = localStorage.getItem("authorityId");

// 上传相关状态
const isUploading = ref(false);
const uploadProgress = ref(0);
const uploadingFiles = ref<string[]>([]);
// 获取审核用户
const availableAuditPersons = ref();
const getAuditRolePersions = async () => {
  const { data } = await GetRoleUsers("333")
  if (data.code == 200) {
    availableAuditPersons.value = data.data;
  } else {
    ElMessage.error(data.msg)
  }
}
// 获取表格状态
const getStatusText = (onlineTask: any) => {

  if (onlineTask.itemReportMaterialStatus == 1) {
    return { type: "primary", text: "待审核" }
  } else if (onlineTask.itemReportMaterialStatus == 2) {
    return { type: "warning", text: "审核中" }
  } else if (onlineTask.itemReportMaterialStatus == 3) {
    return { type: "error", text: "审核未通过" }
  } else if (onlineTask.onlineTime == null) {
    return { type: "success", text: "审核通过" }
  } else {
    return { type: "info", text: "未知" }
  }

};
const createTaskVisible = ref(false);
const updateTaskVisible = ref(false);
const newTask = ref({
  onlineTaskName: '',
  itemItemId: 3,
  reviewTime: '',
  deployTime: ''
});
const handleCreate = () => {
  createTaskVisible.value = true;
  getAllItems()//获取所有的项目
  newTask.value = {
    onlineTaskName: '',
    itemItemId: 3,
    reviewTime: '',
    deployTime: ''
  };
};

// 创建上线任务
const confirmCreateTask = async () => {
  if (!newTask.value.itemItemId || !newTask.value.onlineTaskName) {
    ElMessage.warning('请填写完整信息');
    return;
  }
  // 创建上线任务
  loading.value = true;
  const { data } = await PostCreateReportMaterial({
    "onlineTaskName": newTask.value.onlineTaskName,
    "itemItemId": newTask.value.itemItemId
  })
  if (data.code == 200) {
    loading.value = false;
    createTaskVisible.value = false;
    getAllOnlineTasks();
  } else {
    loading.value = false;
    ElMessage.error(data.msg);
  }

};



// 导出汇报材料
const exportExcel = async () => {
  try {
    const response = await ExportReportMaterialList(searchMode.value);
    console.log(response)
    // 检查是否是错误响应（JSON格式）
    if (typeof response === 'object' && 'code' in response && response.code == 7) {
      ElMessage.error(response.msg);
      return;
    }

    // 如果是Blob类型（Excel文件）
    if (response instanceof Blob) {
      // 创建下载链接
      const url = window.URL.createObjectURL(response);
      const link = document.createElement('a');
      link.href = url;
      let fileName = '汇报材料.xlsx'; // 默认文件名
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请稍后重试');
  }
}


// 修改上线任务
const confirmUpdateTask = async () => {
  if (!newTask.value.onlineTaskName) {
    ElMessage.warning('请填写完整信息');
    return;
  }
  // 修改上线任务
  loading.value = true;
  const { data } = await PostUpdateReportMaterialName({
    "onlineTaskId": openOnlineTask.value,
    "onlineTaskName": newTask.value.onlineTaskName,
  })
  if (data.code == 200) {
    updateTaskVisible.value = false;
    loading.value = false;
    createTaskVisible.value = false;
    ElMessage.success(data.msg);
    getAllOnlineTasks();
  } else {
    loading.value = false;
    ElMessage.error(data.msg);
  }

};



// 上线资源填写或查看
const handleOnlineResources = (row: any) => {
  getAuditRolePersions();
  fileList.value = [];
  scriptFiles.value = [];
  showDialog.value = true;
  openOnlineTask.value = row.ID;
  onlineRemarkForm.value.materialId = row.ID;//操作的上线任务
  onlineRemarkForm.value.materialMsg = row.materialDocumentTip;//上线备注
  onlineRemarkForm.value.submitAuditUUID = row.itemReportMaterialAuditUserUUID;//审核人
  if (row.materialDocument != '') {
    const paths = row.materialDocument.split('|')
    fileList.value = paths.map((path: any) => ({
      uid: Math.random().toString(36).substring(2, 9), // 生成唯一ID
      name: path.split('/').pop().split('_').pop(), // 从路径提取文件名
      url: path, // 完整路径
      status: 'success' // 标记为已上传成功
    }));
  }
}

const submitAuditVisible = ref(false);
const submitAuditUUID = ref('');

// 上线分支
const fileList = ref([]);
const showDialog = ref(false)
const formRef = ref(null)
const scriptFiles = ref([])
// 表单数据
const onlineRemarkForm = ref({
  materialId: 0,//操作的上线任务
  submitAuditUUID: '',//审核人
  materialDocument: '',//上线资源
  materialMsg: '',//上线备注
})

// 提交表单
const handleSubmitOnlineRemark = async () => {
  // 如果正在上传，禁止提交
  if (isUploading.value) {
    ElMessage.warning('文件正在上传中，请稍候...');
    return;
  }

  if (!onlineRemarkForm.value.submitAuditUUID || !fileList.value || !onlineRemarkForm.value.materialMsg) {
    ElMessage.warning('请填写完整信息');
    return
  }
  const fileListResult = fileList.value.map((item: any) => item.url).join('|')
  if (fileListResult != '') {
    onlineRemarkForm.value.materialDocument = fileList.value.map((item: any) => item.url).join('|');
  }
  if (onlineRemarkForm.value.materialDocument === '') {
    ElMessage.error("请等待文件上传成功")
    return;
  }

  const { data } = await PostUploadReportMaterialFile({
    "materialId": openOnlineTask.value,
    "submitAuditUUID": onlineRemarkForm.value.submitAuditUUID,
    "materialDocument": onlineRemarkForm.value.materialDocument,
    "materialMsg": onlineRemarkForm.value.materialMsg
  });
  if (data.code == 200) {
    ElMessage.success(data.msg)
    showDialog.value = false;
    getAllOnlineTasks();
    resetForm()//重置表单
  } else {
    ElMessage.error(data.msg)
  }
}




// 上传后端包
const customUpload = async (options: any) => {
  const { file } = options;

  // 开始上传
  isUploading.value = true;
  uploadProgress.value = 0;
  
  // 添加当前上传的文件到列表
  const currentFileIndex = uploadingFiles.value.length;
  uploadingFiles.value.push(file.name);

  const formData = new FormData();
  formData.append('file', file);
  formData.append('fileType', 'onlineRemark');
  formData.append('fileTypeId', '9'); // 替换为实际值

  try {
    const response = await axios.post('/saferycom/file/upload_file', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'token': localStorage.getItem("TOKEN")
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total) {
          const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          uploadProgress.value = progress;
        }
      }
    });

    // 移除已完成的文件
    uploadingFiles.value.splice(currentFileIndex, 1);
    
    // 如果所有文件都上传完成，重置状态
    if (uploadingFiles.value.length === 0) {
      setTimeout(() => {
        isUploading.value = false;
        uploadProgress.value = 0;
      }, 500);
    }

    return response.data.data;
  } catch (error) {
    console.error('上传失败:', error);
    // 上传失败，移除当前文件并重置状态
    uploadingFiles.value.splice(currentFileIndex, 1);
    if (uploadingFiles.value.length === 0) {
      isUploading.value = false;
      uploadProgress.value = 0;
    }
    throw error;
  }
};
const handleUploadSuccess = (response: any, uploadFile: any) => {
  const filePath = response.resultFilePath;
  // 更新文件列表显示
  uploadFile.url = filePath; // 设置文件URL以便显示
  uploadFile.name = uploadFile.name || filePath.split('/').pop(); // 设置文件名

  ElMessage.success('文件上传成功');
};

const handleUploadError = (error: any) => {
  console.error('上传失败:', error);
  ElMessage.error('文件上传失败');
  // 上传失败时重置状态
  isUploading.value = false;
  uploadProgress.value = 0;
  uploadingFiles.value = [];
};

// 重置表单
const resetForm = () => {
  onlineRemarkForm.value = {
    materialId: 0,
    submitAuditUUID: '',
    materialDocument: '',//上线资源
    materialMsg: '',//上线备注
  }
  fileList.value = [];
  scriptFiles.value = [];
  // 重置上传状态
  isUploading.value = false;
  uploadProgress.value = 0;
  uploadingFiles.value = [];
}
// 历史记录
const historyDialogVisible = ref(false);
const currentHistory = ref<any[]>([]);
const handleHistory = (row: any) => {
  // 模拟获取该任务的历史记录
  getReportMaterialLogs(row);
  historyDialogVisible.value = true;
};


// 获取历史记录项的类型
const getHistoryItemTypeRandomByLength = (action: string) => {
  if (!action) return '';

  const length = action.length;
  const statuses = ['primary', 'success', 'warning', 'danger'] as const;

  if (length === 1 && Math.random() < 0.8) {
    return 'primary'; // 80% 概率返回 primary
  } else if (length === 2 && Math.random() < 0.7) {
    return 'success'; // 70% 概率返回 success
  } else if (length === 3 && Math.random() < 0.6) {
    return 'warning'; // 60% 概率返回 warning
  } else {
    // 其他情况完全随机
    const randomIndex = Math.floor(Math.random() * statuses.length);
    return statuses[randomIndex];
  }
};

// 获取历史记录
const getReportMaterialLogs = async (row: any) => {
  const { data } = await GetGetReportMaterialLogs(row.ID);
  if (data.code == 200) {
    currentHistory.value = data.data;
  } else {

  }
}




// 编辑
const handleEdit = (row: any) => {
  updateTaskVisible.value = true;
  openOnlineTask.value = row.ID;
  newTask.value.onlineTaskName = row.materialName;

};
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该任务吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteOnlineTaskById(row)
  });
};

// 查看审核材料
const lookFileReviewVisible = ref(false);
const handleLookFileReview = (row: any) => {
  openOnlineTask.value = row.ID;
  approveForm.value.processorMySelfNumber = 0;
  approveForm.value.processorCommentToRating = 0;
  approveForm.value.processorCommentToProcessor = '';
  lookFileReviewVisible.value = true;
  currentFiles.value = getCurrentFiles(row.materialDocument)
};
// 材料审核
const fileReviewVisible = ref(false);

const handleFileReview = (row: any) => {
  openOnlineTask.value = row.ID;
  approveForm.value.processorMySelfNumber = 0;
  approveForm.value.processorCommentToRating = 0;
  approveForm.value.processorCommentToProcessor = '';
  fileReviewVisible.value = true;
  currentFiles.value = getCurrentFiles(row.materialDocument)
};
// 对处理人评分
const handleToCreator = (row: any) => {
  openOnlineTask.value = row.ID;
  approveCreatorDialogVisible.value = true;
};

const handleDownload = (row: any) => {
  const link = document.createElement('a');
  link.href = row.downloadUrl;
  link.download = row.name;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  ElMessage.success('开始下载');
};


// 通过评论框
const approveDialogVisible = ref(false)
const approveCreatorDialogVisible = ref(false)
const approveForm = ref({
  reportMaterialId: 0,
  processorMySelfNumber: 0,
  processorCommentToRating: 0,
  processorCommentToProcessor: '',
})
const approveCreatorForm = ref({
  reportMaterialId: 0,
  managerCommentToCreatorNumber: 0,
  creatorrCommentToRating: 0,
  creatorrCommentToProcessor: '',
})
const handleApproveAll = async () => {
  approveDialogVisible.value = true;
};

const submitApprove = () => {
  if (approveForm.value.processorMySelfNumber > 0 || !approveForm.value.processorCommentToProcessor || approveForm.value.processorCommentToRating > 0) {
    ElMessage.warning('请填写必填项');
  }
  auditBy();
  getAllOnlineTasks();
}


const submitCommentApprove = () => {
  if (approveCreatorForm.value.managerCommentToCreatorNumber === 0 || !approveCreatorForm.value.creatorrCommentToProcessor || approveCreatorForm.value.creatorrCommentToRating === 0) {
    ElMessage.warning('所有项必填');
    return
  }
  auditToCreator();
  getAllOnlineTasks();
}


// 对处理人评价
const auditToCreator = async () => {
  const { data } = await PostAuditToCreator({
    "reportMaterialId": openOnlineTask.value,
    "managerCommentToCreatorNumber": approveCreatorForm.value.managerCommentToCreatorNumber,
    "creatorrCommentToRating": approveCreatorForm.value.creatorrCommentToRating,
    "creatorrCommentToProcessor": approveCreatorForm.value.creatorrCommentToProcessor,
  })
  if (data.code == 200) {
    ElMessage.success(data.msg);
    approveCreatorDialogVisible.value = false
    getAllOnlineTasks();
  } else {
    ElMessage.error(data.msg);
  }
}


const auditBy = async () => {
  const { data } = await PostAuditBy({
    "reportMaterialId": openOnlineTask.value,
    "processorMySelfNumber": approveForm.value.processorMySelfNumber,
    "processorCommentToRating": approveForm.value.processorCommentToRating,
    "processorCommentToProcessor": approveForm.value.processorCommentToProcessor,
  });
  if (data.code == 200) {
    ElMessage.success(data.msg)
    fileReviewVisible.value = false;
    approveDialogVisible.value = false;
    getAllOnlineTasks();
  } else {
    ElMessage.error(data.msg)
  }
}


const notByMsg = ref('');
const handleReject = () => {
  ElMessageBox.prompt('请输入驳回原因', '驳回', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请详细说明驳回原因',
    // 添加 beforeClose 钩子函数
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        if (!instance.inputValue) {
          ElMessage.error("请填写驳回原因");
          // 阻止关闭
          return false;
        }
        // 允许关闭
        done();
      } else {
        // 取消操作直接关闭
        done();
      }
    }
  }).then(({ value }) => {
    notByMsg.value = value;
    auditNotBy();
  }).catch(() => { });
};

// 驳回审核
const auditNotBy = async () => {
  const { data } = await PostAuditNotBy({
    "reportMaterialId": openOnlineTask.value,
    "notByMsg": notByMsg.value,
  })
  if (data.code == 200) {
    fileReviewVisible.value = false;
    getAllOnlineTasks();
    ElMessage.success(data.msg);
  } else {
    ElMessage.success(data.msg);
  }
}

const getCurrentFiles = (filesPath: string) => {
  const filesPaths = filesPath.split('|');

  const currentFiles = filesPaths.map(filePath => {
    const filenameWithExt = filePath.split('/').pop() || '';

    const parts = filenameWithExt.split('_');

    const submitter = parts.length > 1 ? parts[1] : 'Unknown';

    const name = parts.length > 3 ? parts.slice(3).join('_') : filenameWithExt;

    return {
      name: name,
      submitter: submitter,
      downloadUrl: filePath
    };
  });

  return currentFiles;
};

const currentFiles = ref();

const previewFile = (row: any) => {
  const officeOnlineUrl = `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(row.downloadUrl)}`;
  window.open(officeOnlineUrl, '_blank', 'noopener,noreferrer');
};



// 撤销审核
const handleReturnMeetingNotes = (row: any) => {
  ElMessageBox.confirm('确定要撤销需要审核的汇报文档吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    returnReportMaterialAudit(row)
  });
};

//撤销审核
const returnReportMaterialAudit = async (row: any) => {
  const { data } = await GetReturnReportMaterialAudit(row.ID)
  if (data.code == 200) {
    ElMessage.success(data.msg)
    getAllOnlineTasks();
  } else {
    ElMessage.error(data.msg)
  }
}


// 删除上线任务
const deleteOnlineTaskById = async (row: any) => {
  const { data } = await GetDeleteReportMaterialById(row.ID);
  if (data.code == 200) {
    ElMessage.success(data.msg)
    getAllOnlineTasks();
  } else {
    ElMessage.error(data.msg)
  }
}

// 获取所有项目名称
const allItems = ref();
const getAllItems = async () => {
  const { data } = await getItemList()
  if (data.code == 200) {
    allItems.value = data.data;
  }
}



//分页查询
const handleBugListPageChange = (page: number) => {
  currentPage.value = page
  getAllOnlineTasks();
}


const handleDateChange = (val: any) => {
  searchMode.value.beginTime = val[0]
  searchMode.value.endTime = val[1]
  getAllOnlineTasks();
}
const handleStatusChange = (val: any) => {
  searchMode.value.mySelf = val
  getAllOnlineTasks();
}
// 模糊查询
const handleSearch = () => {
  searchMode.value.onlineTaskName = searchKey.value
  getAllOnlineTasks();
}

const searchMode = ref({
  "onlineTaskName": "",
  "mySelf": 1,
  "beginTime": null,
  "endTime": null,
  "page": currentPage.value,
  "pageSize": pageSize.value
})


const tableData = ref();
// 获取所有的上线任务
const getAllOnlineTasks = async () => {
  loading.value = false;
  searchMode.value.page = currentPage.value
  const { data } = await PostgetReportMaterialList(searchMode.value)

  if (data.code == 200) {
    tableData.value = data.data.list
    currentPage.value = data.data.page
    pageSize.value = data.data.pageSize
    total.value = data.data.total
    // loading.value = false;
  } else {
    ElMessage.error(data.msg);
  }
}

// TODO 预览文件
const handlePreviewDocument = (url: string) => {
  let file = handleFileName(url);
  if (file.url.includes('Img') || file.url.includes('.pdf') || file.url.includes('.txt') || file.url.includes('.png') || file.url.includes('.gif') || file.url.includes('.jpge')) {
    window.open(`${'http://192.168.0.91:19081' + url}`, '_blank');
    return;
  } else {
    openPreviewInNewWindow(url, file.fileName);
  }
};



// 页面初始化调用接口
onMounted(async () => {
  getAllOnlineTasks();
});
onBeforeMount(async () => {
  getAllItems();
})

</script>

<style scoped>
.el-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #e5e7eb;
}

.el-input :deep(.el-input__wrapper):hover {
  box-shadow: 0 0 0 1px #409eff;
}

.el-select :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #e5e7eb;
}

.el-select :deep(.el-input__wrapper):hover {
  box-shadow: 0 0 0 1px #409eff;
}

input[type="date"]::-webkit-calendar-picker-indicator {
  display: none;
}



/* 上线任务弹框样式 */
.script-tabs {
  @apply border border-gray-200 rounded-md p-2 w-full;
}

:deep(.el-tabs__content) {
  @apply p-0;
}

.script-textarea {
  min-height: 200px;
  @apply w-full;
}

:deep(.el-textarea__inner) {
  min-height: 200px !important;
  @apply w-full;
}

:deep(.el-upload__tip) {
  @apply mt-1;
}

.upload-demo {
  @apply w-full;
}

:deep(.el-upload) {
  @apply w-full;
}

:deep(.el-upload-dragger) {
  @apply w-full p-4;
}

.script-tabs {
  @apply border border-gray-200 rounded-md p-2 w-full;
}

:deep(.el-tabs__content) {
  @apply p-0;
}

:deep(.el-upload__tip) {
  @apply mt-1;
}

:deep(.el-icon--upload) {
  @apply text-2xl mb-2 text-gray-400;
}

:deep(.el-upload__text) {
  @apply text-sm text-gray-500;
}

/* 自定义上传进度条样式 */
.upload-progress-container {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 1px solid #bae6fd;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.upload-progress-bar {
  background: linear-gradient(90deg, #3b82f6 0%, #6366f1 100%);
  box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
  position: relative;
  overflow: hidden;
}

.upload-progress-bar::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% {
    left: -100%;
  }
  100% {
    left: 100%;
  }
}

.upload-progress-glow {
  box-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
  animation: glow 2s ease-in-out infinite alternate;
}

@keyframes glow {
  from {
    box-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
  }
  to {
    box-shadow: 0 0 20px rgba(59, 130, 246, 0.8);
  }
}
</style>
